package com.finstate.web;

import java.util.List;

import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.finstate.domain.Rate;
import com.finstate.service.RateService;
import com.finstate.util.MessagesUtil;

@Controller
@RequestMapping("/rates")
public class RateController {

	private RateService rateService;

	private final Log logger = LogFactory.getLog(getClass());

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView rates() {
		ModelAndView mav = new ModelAndView("finstate.index.view");
		List<Rate> ratesList = rateService.getRates();
		MessagesUtil.getMessage("header.title", "en");
		logger.info(ratesList);
		mav.addObject(ratesList);
		mav.addObject(new Rate());
		return mav;
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView addRate(@ModelAttribute("rate") @Valid Rate rate, BindingResult result, SessionStatus status) {
		logger.info(rate);	
		if (result.hasErrors()) {
			return rates();
		}
		rateService.addRate(rate);
		status.setComplete();
		return new ModelAndView("redirect:/rates");
	}

	@RequestMapping(value = "/delete/{rateId}", method = RequestMethod.GET)
	public String deleteRate(@PathVariable("rateId") Long rateId) {
		logger.info(rateId);
		rateService.deleteRate(rateId);
		return "redirect:/rates";
	}

	@Autowired	
	public void setRateService(RateService rateService) {
		this.rateService = rateService;
	}
}
